﻿#include "TlvCodePanel.h"
#include "ui_TlvCodePanel.h"
#include "services/Task/TlvCmdTask.h"
#include "services/Task/TlvCodeTask.h"
#include "components/Toast/Toast.h"

#include <QDebug>

TlvCodePanel::TlvCodePanel(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TlvCodePanel)
{
    ui->setupUi(this);

    ui->btnRun->setOnIcon(QIcon(":/imgs/stop.png"));

    TlvCodeTask* task = TlvCodeTask::instance();
    connect(task, &TlvCodeTask::taskFinished, this, [=](){
        ui->btnRun->setIconStatus(false);
    });
}

TlvCodePanel::~TlvCodePanel()
{
    delete ui;
}

void TlvCodePanel::setTitle(const QString &title)
{
    m_title = title;
}

void TlvCodePanel::setCode(const QString &code)
{
    ui->wEditor->setText(code);
}

CodePageModel TlvCodePanel::toCodeModel()
{
    static uint16_t tabID = 1;
    CodePageModel res;
    res.name = QString("tab-%1").arg(tabID++);
    res.title = m_title;
    res.code = ui->wEditor->code();
    return res;
}

void TlvCodePanel::on_btnRun_clicked()
{

    TlvCodeTask* task = TlvCodeTask::instance();
    IconButton* btn = ui->btnRun;

    if (btn->isOn() && task->isRunning()) {  // 这是判断运行的任务是否是当前选择的任务
        task->stop();
        btn->setIconStatus(false);
        Toast::info( ITask::INFO_TASK_STOPPED(task->taskName()) );
        return;
    }
    if (task->isRunning()) {  // 其它Code任务正在运行
        Toast::warning( ITask::WARN_TASK_IS_RUNNING(task->taskName()) );
        return;
    }
    if (TlvCmdTask::instance()->isRunning()) {  // Cmd任务正在运行
        Toast::warning( ITask::WARN_TASK_IS_RUNNING(TlvCmdTask::instance()->taskName()) );
        return;
    }
    btn->setIconStatus(true);
    task->setTaskName(QString("Code.%1").arg(m_title));
    task->setCode(ui->wEditor->code());
    task->setCodeType(TlvCodeTask::JavaScript);
    task->start();
}
